import { message } from "antd";
import axios, {
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from "axios";

import { ResultEnum } from "@/enums/ResultEnum";
import { clearToken, clearUserInfo, getToken } from "@/utils/auth";

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const accessToken = getToken();
    if (accessToken) {
      config.headers["Token"] = accessToken;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, data, tips, message: messageInfo } = response.data;
    if (code === ResultEnum.SUCCESS) {
      return data;
    }
    message.error(tips ?? messageInfo ?? "系统错误");
    return Promise.reject(new Error((tips ?? messageInfo) || "Error"));
  },
  (error: any) => {
    const { response } = error;
    if (response) {
      // 非 2xx 状态码处理 401、403、500 等
      const { status } = response;
      // token 过期，退出
      if (status === ResultEnum.ACCESS_TOKEN_INVALID) {
        clearToken();
        clearUserInfo();
        window.location.href = "/login";
      } else if (status === ResultEnum.REFRESH_TOKEN_INVALID) {
        return Promise.reject(new Error("Error"));
      } else {
        message.error("系统出错");
      }
    }
    return Promise.reject(error.message);
  }
);

const request = {
  post: <T, R>(url: string, data?: T, config: AxiosRequestConfig = {}): Promise<R> => {
    return service({ url, method: "post", data: { ...data, version: "1.0" }, ...config });
  },
  get: <T, R>(url: string, params?: T, config: AxiosRequestConfig = {}): Promise<R> => {
    return service({ url, method: "get", params, ...config });
  },
  delete: <T, R>(url: string, params?: T, config: AxiosRequestConfig = {}): Promise<R> => {
    return service({ url, method: "delete", params, ...config });
  },
  put: <T, R>(url: string, data?: T, config: AxiosRequestConfig = {}): Promise<R> => {
    return service({ url, method: "put", data, ...config });
  },
};

export default request;
